import { ThemeProvider } from '@/components/ThemeProvider.tsx';
import DialogManager from '@/dialogs';
import Broadcast from '@/components/Broadcast.tsx';
import { useEffectAsync } from '@/utils/hook.ts';
import { bindMarket, getApiPlans } from '@/api/v1.ts';
import { useDispatch } from 'react-redux';
import {
    stack,
    updateMasks,
    updateSupportModels,
    useMessageActions
} from '@/store/chat.ts';
import { dispatchSubscriptionData, setTheme } from '@/store/globals.ts';
import { infoEvent } from '@/events/info.ts';
import { setForm } from '@/store/info.ts';
import { themeEvent } from '@/events/theme.ts';
import { useEffect } from 'react';

function AppProvider() {
    const dispatch = useDispatch();
    const { receive } = useMessageActions();

    useEffect(() => {
        infoEvent.bind(data => dispatch(setForm(data)));
        themeEvent.bind(theme => dispatch(setTheme(theme)));

        stack.setCallback(async (id, message) => {
            await receive(id, message);
        });
    }, []);

    useEffectAsync(async () => {
        updateSupportModels(dispatch, await bindMarket());
        dispatchSubscriptionData(dispatch, await getApiPlans());
        await updateMasks(dispatch);
    }, []);

    return (
        <>
            <Broadcast />
            <ThemeProvider />
            <DialogManager />
        </>
    );
}

export default AppProvider;
